#include "WifiInfoInputEdit.hpp"

WifiInfoInputEdit::WifiInfoInputEdit(QWidget *parent)
    : QWidget(parent)
{
    this->ssidLineEdit     = new QLineEdit{this};
    this->passwordLineEdit = new QLineEdit{this};
    this->cryptoComboBox   = new QComboBox{this};

    for (auto [name, type] : cryptoPairs) {
        this->cryptoComboBox->addItem(name,
                                      QVariant::fromValue(type));
    }
    this->hiddenRadio = new QRadioButton{this};
    this->hiddenRadio->setChecked(false);
    auto mainLayout = new QGridLayout{this};
    mainLayout->addWidget(new QLabel{"SSID:", this}, 0, 0);
    mainLayout->addWidget(this->ssidLineEdit, 0, 1);
    mainLayout->addWidget(new QLabel{"Password:", this}, 1, 0);
    mainLayout->addWidget(this->passwordLineEdit, 1, 1);
    mainLayout->addWidget(new QLabel{"Encryption:", this}, 2, 0);
    mainLayout->addWidget(this->cryptoComboBox, 2, 1);
    mainLayout->addWidget(new QLabel{"Hidden:", this}, 3, 0);
    mainLayout->addWidget(this->hiddenRadio, 3, 1);
    QObject::connect(
        this->ssidLineEdit,
        &QLineEdit::textChanged,
        this,
        &WifiInfoInputEdit::onWifiInfoChanged);
    QObject::connect(
        this->passwordLineEdit,
        &QLineEdit::textChanged,
        this,
        &WifiInfoInputEdit::onWifiInfoChanged);
    QObject::connect(
        this->cryptoComboBox,
        QOverload<int>::of(&QComboBox::currentIndexChanged),
        this,
        &WifiInfoInputEdit::onWifiInfoChanged);
    QObject::connect(
        this->hiddenRadio,
        &QRadioButton::toggled,
        this,
        &WifiInfoInputEdit::onWifiInfoChanged);
}

QString WifiInfoInputEdit::getWifiInfoString() const
{
    auto result = QString{};

    result += "WIFI:";
    result += "S:" + this->getSSID() + ";";
    result += "T:" + this->getEncryptionTypeStr() + ";";
    result += "P:" + this->getPassword() + ";";
    result += "H:" + this->getHiddenStr() + ";";
    result += ";";
    return result;
}

void WifiInfoInputEdit::onWifiInfoChanged()
{
    emit infoChanged();
}

QString WifiInfoInputEdit::getSSID() const
{
    return this->ssidLineEdit->text();
}

QString WifiInfoInputEdit::getPassword() const
{
    return this->passwordLineEdit->text();
}

QString WifiInfoInputEdit::getEncryptionTypeStr() const
{
    auto result = QString{};
    for (auto [name, type] : cryptoPairs) {
        auto currentType = this->cryptoComboBox->currentData().value<EncryptionType>();
        if (currentType == type) {
            result = name;
            break;
        }
    }
    return result;
}
QString WifiInfoInputEdit::getHiddenStr() const
{
    return this->hiddenRadio->isChecked() ? "HIDDEN" : "VISIBLE";
}

void WifiInfoInputEdit::clear()
{
    this->ssidLineEdit->clear();
    this->passwordLineEdit->clear();
    this->cryptoComboBox->setCurrentIndex(0);
    this->hiddenRadio->setChecked(false);
}
